const express = require('express')
const bodyParser = require('body-parser');
const low = require('lowdb')
const fileAsync = require('lowdb/lib/storages/file-async')

// Create server
const app = express()

app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json({type: 'application/*+json'}))

// Start database using file-async storage
const db = low('db.json', {storage: fileAsync})

// Routes
// GET /posts/:id
app.get('/posts/:id', (req, res) => {
    console.log(req.body);
    console.log(req.params);
    const post = db.get('posts').find({
        id: parseInt(req.params.id)
    }).value();

    res.json(post)
})

// POST /posts
app.post('/posts', (req, res) => {
    console.log(req.body);
    console.log(req.params);
    db.get('posts').push(req.body).last().assign({id: Date.now()}).write().then(post => res.send(post))
})

// after
async function create(post) {
    const result = await db.get('posts').push(post).write()
}

// Init
// db.defaults({posts: []}).write().then(() => {
//     app.listen(3000, () => console.log('Server is listening'))
// });
app.listen(3000, () => console.log('Server is listening'));
